package org.suwenqian.audiovideosummary.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.suwenqian.audiovideosummary.config.QiNiuYunProps;

import java.io.InputStream;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import static org.suwenqian.audiovideosummary.common.constant.UploadReturnMapConstant.UPLOAD_Return_HASH_Object;
import static org.suwenqian.audiovideosummary.common.constant.UploadReturnMapConstant.UPLOAD_Return_KEY_Object;

@Slf4j
@Component
@RequiredArgsConstructor
public class QiNiuUploaderUtil {
    private final UploadManager uploadManager;
    private final Auth auth;
    private final QiNiuYunProps prop;

    /* 1. 本地文件路径上传 */
    public Map<String, String> uploadPath(Path filePath, String key) throws QiniuException {
        String token = auth.uploadToken(prop.getBucket());
        Response resp = uploadManager.put(filePath.toFile(), key, token);
        return parseKey(resp);
    }

    /* 2. 字节数组上传（小文件 < 10 MB） */
    public Map<String, String> uploadBytes(byte[] data, String key) throws QiniuException {
        String token = auth.uploadToken(prop.getBucket());
        Response resp = uploadManager.put(data, key, token);
        return parseKey(resp);
    }

    /* 3. InputStream 上传（不想落盘时用） */
    public Map<String, String> uploadStream(InputStream in, String key, long size) throws QiniuException {
        String token = auth.uploadToken(prop.getBucket());
        Response resp = uploadManager.put(in, key, token, null, null);
        return parseKey(resp);
    }

    /* 4. 大文件分片上传（> 100 MB 推荐） */
    public Map<String, String> uploadBigFile(Path filePath, String key) throws QiniuException {
        String token = auth.uploadToken(prop.getBucket());
        // 自动分片、并发上传
        Response resp = uploadManager.put(filePath.toFile(), key, token,
                null, null, true); // true = 启用断点续传
        return parseKey(resp);
    }

    private Map<String, String> parseKey(Response resp) throws QiniuException {
        DefaultPutRet ret = new Gson().fromJson(resp.bodyString(), DefaultPutRet.class);
        log.info("[音视频文件上传] -- 文件上传成功， --七牛云key: {}, --七牛云哈希编码： {}", ret.key, ret.hash);
        Map<String, String> reMap = new HashMap<>();
        reMap.put(UPLOAD_Return_KEY_Object, ret.key);
        reMap.put(UPLOAD_Return_HASH_Object, ret.hash);
        return reMap;   // 回写 key 用于存库
    }
}
